//
//  HYReplyViewController.m
//  HaiYue
//
//  Created by skyline on 2018/5/25.
//  Copyright © 2018年 skyline. All rights reserved.
//

#import "HYReplyViewController.h"
#import "HYInfoCommentCell.h"
@interface HYReplyViewController ()<UITableViewDelegate,UITableViewDataSource,HYTextViewDelegate>
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) HYReplyList *list;
@property (nonatomic, strong) HYView *replyBackView;
@property (nonatomic, strong) HYTextView *textview;
@property (nonatomic, strong) HYButton *replyBtn;
@property (nonatomic, assign) CGFloat cellH1;
@property (nonatomic, assign) CGFloat cellH2;
@end

@implementation HYReplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"回复游戏详情";
    self.textview.hidden = NO;
    [CCNotice addObs:self sel:@selector(actionForKeyboardShow:) name:UIKeyboardWillChangeFrameNotification obj:nil];
    [CCNotice addObs:self sel:@selector(actionForZanCaiReplyInReplyVC:) name:HYInfoCommentCellZan obj:nil];
    [CCNotice addObs:self sel:@selector(actionForZanCaiReplyInReplyVC:) name:HYInfoCommentCellCai obj:nil];
    // Do any additional setup after loading the view.
}

- (UITableView *)tableview
{
    if (!_tableview)
    {
        _tableview = [[UITableView alloc] init];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.estimatedRowHeight = 0;
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.mj_header = [HYRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(actionForReplyRefresh)];
        _tableview.mj_footer = [HYRefreshFooder footerWithRefreshingTarget:self refreshingAction:@selector(actionForReplyMore)];
        
        [self.view addSubview:_tableview];
        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view);
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.bottom.equalTo(self.view).with.offset(-SCREEN_HEIGHT / 8);
        }];
    }
    return _tableview;
}

- (HYView *)replyBackView
{
    if (!_replyBackView)
    {
        _replyBackView = [[HYView alloc] initWithColor:CELL_LINE_COLOR];
        [self.view addSubview:_replyBackView];
        [_replyBackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view);
            make.right.equalTo(self.view);
            make.bottom.equalTo(self.view);
            make.height.mas_equalTo(SCREEN_HEIGHT / 8);
        }];
    }
    return _replyBackView;
}
- (HYTextView *)textview
{
    if (!_textview)
    {
        _textview = [[HYTextView  alloc] init];
        _textview.placholder = @"输入回复内容";
        _textview.returnKeyType = UIReturnKeyDone;
        _textview.hydelegate = self;
        _textview.layer.cornerRadius = GAP / 2;
        [self.replyBackView addSubview:_textview];
        [_textview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.replyBackView).with.offset(GAP);
            make.left.equalTo(self.replyBackView).with.offset(GAP);
            make.right.equalTo(self.replyBtn.mas_left).with.offset(-GAP);
            make.bottom.equalTo(self.replyBackView).with.offset(-GAP);
        }];
    }
    return _textview;
}
- (HYButton *)replyBtn
{
    if (!_replyBtn)
    {
        _replyBtn = [[HYButton alloc] initWithTitle:@"发表" backColor:THEME_COLOR];
        _replyBtn.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightLight];
        [_replyBtn addTarget:self action:@selector(actionForReplyBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.replyBackView addSubview:_replyBtn];
        [_replyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.replyBackView);
            make.right.equalTo(self.replyBackView).with.offset(-GAP);
            make.width.mas_equalTo(60);
        }];
    }
    return _replyBtn;
}
- (void)setList:(HYReplyList *)list
{
    if (_list != list)
    {
        _list = list;
        [self.tableview reloadData];
    }
}
//int commentid = getParaToInt("commentid",0);
//String text = getPara("text");
- (void)actionForReplyBtn
{
    if ([self.textview.text length] < 1)
        return [CCAlert showMessage:@"不能回复空内容" hidden:nil];
    
    [self startHUD];
    
    [CCHttp post:API_DO_REPLY para:@{@"commentid":self.model.commentid,@"text":self.textview.text} success:^(id  _Nonnull response) {
        [self endHUD];
        [self requesthttps:nil];
        [self endEdit];
        self.textview.text = @"";
    } fail:^(NSError * _Nonnull error) {
        [self endHUD];
    }];
    
//    [HYHttps post:API_DO_REPLY para:@{@"commentid":self.model.commentid,@"text":self.textview.text} complete:^(id response) {
//        [self endHUD];
//        [self requesthttps:nil];
//        [self endEdit];
//        self.textview.text = @"";
//    } fail:^(NSDictionary *dict) {
//        [self endHUD];
//    }];
}

//点赞/踩/回复
//1点赞 0 取消 -1踩int commentid = getParaToInt("commentid",0);
//int val = getParaToInt("val",0);//ConstantApp._state_do;
- (void)actionForZanCaiReplyInReplyVC:(NSNotification *)notify
{
    NSString *api = [[notify.userInfo valueForKey:@"replyid"] length] > 0 ?API_REPLY_LIKE:API_COMMENT_LIKE;
    [CCHttp post:api para:notify.userInfo success:^(id  _Nonnull response) {
        if ([[response valueForKey:@"retcode"] intValue] == 100 && [[response valueForKey:@"state"] hasPrefix:@"success"])
            [CCNotice post:HYInfoCommentCellCallBack obj:notify.object info:notify.userInfo];
        else
            [CCAlert showMessage:[response valueForKey:@"state"] hidden:nil];
    } fail:^(NSError * _Nonnull error) {
        
    }];
//    [HYHttps post:API_REPLY_LIKE para:notify.userInfo  complete:^(id response) {
//        if ([[response valueForKey:@"retcode"] intValue] == 100 && [[response valueForKey:@"state"] hasPrefix:@"success"])
//            [CCNotice post:HYInfoCommentCellCallBack obj:notify.object info:notify.userInfo];
//        else
//            [CCAlert showMessage:[response valueForKey:@"state"] hidden:nil];
//    } fail:^(NSDictionary *dict) {
//
//    }];
}
- (void)actionForReplyRefresh
{
    [self requesthttps:nil];
}
- (void)actionForReplyMore
{
    if (self.list.more)
        [self requesthttps:self.list.more];
    else
        self.tableview.mj_footer.state = MJRefreshStateNoMoreData;
}
- (void)requesthttps:(NSString *)more
{
    NSString *api = more?more:API_ARTICLE_REPLY;
    
    [CCHttp post:api para:@{@"commentid":self.model.commentid} success:^(id  _Nonnull response) {
        if (!more)
        {
            self.list = [HYReplyList mj_objectWithKeyValues:response];
            [self.tableview.mj_header endRefreshing];
            self.tableview.mj_footer.state = MJRefreshStateIdle;
        }
        else
        {
            HYReplyList *newlist = [HYReplyList mj_objectWithKeyValues:response];
            NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.list.list];
            [tempArr addObjectsFromArray:newlist.list];
            newlist.list = tempArr;
            self.list = newlist;
            [self.tableview.mj_footer endRefreshing];
        }
    } fail:^(NSError * _Nonnull error) {
        [self.tableview.mj_header endRefreshing];
        [self.tableview.mj_footer endRefreshing];
    }];
    
//    [HYHttps post:api para:@{@"commentid":self.model.commentid} complete:^(id response) {
//        if (!more)
//        {
//            self.list = [HYReplyList mj_objectWithKeyValues:response];
//            [self.tableview.mj_header endRefreshing];
//        }
//        else
//        {
//            HYReplyList *newlist = [HYReplyList mj_objectWithKeyValues:response];
//            NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.list.list];
//            [tempArr addObjectsFromArray:newlist.list];
//            newlist.list = tempArr;
//            self.list = newlist;
//            [self.tableview.mj_footer endRefreshing];
//        }
//    } fail:^(NSDictionary *dict) {
//        [self.tableview.mj_header endRefreshing];
//    }];
}
- (void)endEdit
{
    [self.textview resignFirstResponder];
    [self.tableview mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).with.offset(-SCREEN_HEIGHT / 8);
    }];
    [UIView animateWithDuration:0.25 animations:^{
        self.replyBackView.transform = CGAffineTransformIdentity;
    }];
}
- (void)actionForKeyboardShow:(NSNotification *)notify
{
    //获取键盘的高度
    NSValue *aValue = [notify.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardHeight = [aValue CGRectValue].size.height;//键盘的高度
    //获取键盘动画时间
    float time = [notify.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [self.tableview mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).with.offset(-SCREEN_HEIGHT / 8 - keyboardHeight);
    }];
    [UIView animateWithDuration:time animations:^{
        self.replyBackView.transform = CGAffineTransformMakeTranslation(0, -keyboardHeight);
    }];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"])
    {
        [self endEdit];
        return NO;
    }
    return YES;
}
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) return 1;
    else return self.list.list.count;//多处的一个cell的下划线
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        NSString *idetifier = @"headerview";
        HYInfoCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:idetifier];
        if (!cell)
        {
            cell = [[HYInfoCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idetifier];
        }
        cell.style = HYInfoCommentCellStyleSimple;
        cell.commentModel = self.model;
        self.cellH1 = CGRectGetHeight(cell.bounds);
        return cell;
    }
    else {
        NSString *identifier2 = [NSString stringWithFormat:@"HYInfoCommentCell%ld",(long)indexPath.row];
        HYInfoCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier2];
        if (!cell)
        {
            cell = [[HYInfoCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier2];
        }
        cell.replyModel = self.list.list[indexPath.row];
        self.cellH2 = CGRectGetHeight(cell.bounds);
        return cell;
    }
}

#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) return self.cellH1;
    else  return self.cellH2;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0)
    {
        HYView *view = [[HYView alloc] initWithColor:[UIColor whiteColor]];
        HYView *line = [[HYView alloc] initWithColor:CELL_LINE_COLOR];
        HYLabel *label = [[HYLabel alloc] initWithText:@"网友回复:" textColor:TEXT_BLACK_COLOR textFont:[UIFont systemFontOfSize:TitleFont weight:UIFontWeightRegular]];
        [view addSubview:line];
        [view addSubview:label];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view).with.offset(-1);
            make.left.equalTo(view);
            make.right.equalTo(view);
            make.height.mas_equalTo(GAP / 2);
        }];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(line.mas_bottom).with.offset(GAP);
            make.left.equalTo(view).with.offset(GAP);
        }];
        return view;
    }
    else return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) return 35;
    else return 0;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.style = HYViewNaviBarStyleOnlyLeftBtn;
    [self requesthttps:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    [CCNotice rmObs:self name:UIKeyboardWillChangeFrameNotification obj:nil];
    [CCNotice rmObs:self name:HYInfoCommentCellZan obj:nil];
    [CCNotice rmObs:self name:HYInfoCommentCellCai obj:nil];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
